<?php

/**
 * 文件上传
 */


// function upload()
// {
//     if ($_FILES['up']['error'] > 0) {
//         return '上传失败，请检查文件类型或大小';
//     }
//
//     $uploadFile = 'uploads/' . time() . '.' . pathinfo($_FILES['up']['name'])['extension'];
//     if (is_uploaded_file($_FILES['up']['tmp_name'])) {
//         if (move_uploaded_file($_FILES['up']['tmp_name'], $uploadFile)) {
//             return '上传成功:' . $uploadFile;
//         }
//     }
//
//     return '上传失败!';
// }

/**
 * 文件上传类 支持单文件，多文件上传
 */
class file
{
    protected $files = [];

    public function upload($path = '')
    {
        $sava_files = [];

        // 获取上传的文件内容
        $this->get_upload_files();

        self::make_dir($path);

        foreach ($this->files as $k => $file) {
            if ($file['error'] == 0) {
                if (is_uploaded_file($file['tmp_name'])) {
                    $save = $path . $k . time() . '.' . pathinfo($file['name'])['extension'];
                    if (move_uploaded_file($file['tmp_name'], $save)) {
                        $saveFiles[] = $save;
                    }
                }
            }
        }

        return $sava_files;
    }

    protected function get_upload_files()
    {
        $files = [];
        foreach ($_FILES as $field) {
            if (is_array($field['name'])) {
                foreach ($field['name'] as $id => $name) {
                    $files[] = [
                        'name' => $name,
                        'type' => $field['type'][$id],
                        'error' => $field['error'][$id],
                        'size' => $field['size'][$id],
                        'tmp_name' => $field['tmp_name'][$id],
                    ];
                }
            } else {
                $files[] = $field;
            }
        }
        return $this->files = $files;
    }

    protected static function make_dir($path = '')
    {
        if (!is_dir($path)) {
            return mkdir($path, 0755, true);
        }
    }

    /**
     * 文件下载
     * @param string $file
     * @return false
     */
    public function download($file = '')
    {
        if (!file_exists($file)) {
            return false;
        }

        //指定下载文件类型为二进制
        header("Content-type:application/octet-stream");

        //获取文件名
        $fileName = basename($file);

        //下载窗口显示文件名
        header("Content-Disposition:attachment;filename={$fileName}");

        //文件尺寸单位
        header("Accept-ranges:bytes");

        //文件大小
        header("Accept-length:" . filesize($file));

        //读取文件内容供下载
        readfile($file);
    }

}


$file = new file();
// 文件上传
// $file->upload('upload/' . date('Y-m-d'));

// 文件下载
$file->download('D:\www\dscmall-x\storage\app\public\images\logo.gif');

